package com.example.se2_funmessages;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener {
	
	String response = null;
	int count;
	int countSaved;

	Activity a= this;
	 
	private final static int INTERVAL = 1000 * 10; //2 minutes
	Handler m_handler = new Handler();
	Button newM;
	Button saved;
	Boolean ready = false;
	Runnable m_handlerTask = new Runnable()
	{
	     @Override 
	     public void run() {
	          checkMessage();
	        if (ready){  
	      	DatabaseHandler dbh = new DatabaseHandler(a);
			count = dbh.getMessageCount();
			countSaved = dbh.getSavedMessageCount();
			dbh.close();
			newM.setText("View New Messages (" + count + ")");
			saved.setText("View Saved Messages (" + countSaved + ")");
	        }
	          m_handler.postDelayed(m_handlerTask, INTERVAL);
	     }
	};
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

		saved = (Button) findViewById(R.id.button2);
		saved.setOnClickListener(this);
		
		newM = (Button) findViewById(R.id.button1);
		newM.setOnClickListener(this);
		ready = true;
		
		Button send = (Button) findViewById(R.id.button3);
		send.setOnClickListener(this);
		 
		Button logOut = (Button) findViewById(R.id.button4);
		logOut.setOnClickListener(this);
		
		Intent intent = getIntent();
		String userName = intent.getStringExtra(Login.UN);
		TextView textName = (TextView) findViewById(R.id.textView2);
		textName.setText(userName);
		startRepeatingTask();
	}

	@Override
	public void onBackPressed() {
	}
	/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.setting_menu, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.sendMessage:
			Intent sendMessage = new Intent(this, SendMessage.class);
			startActivity(sendMessage);
			return true;

		}
		return true;
	}
*/
	public void view(View v) {
		Intent i = new Intent(this, ViewMessage.class);
		startActivity(i);
	}
	
	public void checkMessage()
	{
		Log.d("HERE","here1");
		new GetTimeUpdate().execute(getApplicationContext());
		
	}

	public class GetTimeUpdate extends AsyncTask<Context, Context, Context> {


		
		
		@Override
		protected Context doInBackground(Context... params) {
			
			
			
			int userNum = -1;


					
					DatabaseHandler dbh = new DatabaseHandler(params[0]);

					userNum = dbh.getUserNum();

					
					dbh.close();

					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(
							"http://softeng.cs.uwosh.edu/students/cs342g3/sendMessage.php?user_id="
									+ userNum);
					try {

						// Execute HTTP Post Request

						ResponseHandler<String> responseHandler = new BasicResponseHandler();
						response = httpclient.execute(httppost,
								responseHandler);
						
						response = response.trim();

						if (!response.equals("none")) {

							return params[0];
						}

					} catch (ClientProtocolException e) {
						// Toast.makeText(params[0], "CPE response " +
						// e.toString(), Toast.LENGTH_LONG).show();
						// TODO Auto-generated catch block
					} catch (IOException e) {
 
						// TODO Auto-generated catch block
					}
					return null;
		}


		

		
		@Override
		protected void onPostExecute(Context values)
		{
			
		
			if (values != null)
			{
//				Toast.makeText(values, "You have a message", Toast.LENGTH_SHORT)
//				.show();
		
				
				String ns = Context.NOTIFICATION_SERVICE;
				NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
				
				int icon = R.drawable.ic_launcher;
				CharSequence tickerText = "You Have a new Message!";
				long when = System.currentTimeMillis();
				
				Notification notification = new Notification(icon, tickerText, when);
				
				Context context = getApplicationContext();
				CharSequence contentTitle = "FunMessages";
				CharSequence contentText = "You Have a new Message!";
				Intent notificationIntent = new Intent(values, NewMessage.class);
				PendingIntent contentIntent = PendingIntent.getActivity(values, 0, notificationIntent, 0);
				notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;

				notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
				
				final int HELLO_ID = 1;

				mNotificationManager.notify(HELLO_ID, notification);
				
			DatabaseHandler dbh = new DatabaseHandler(values);
			
			dbh.insertMessagesIntoDatabase(response);
			
			dbh.close();
			}
				

			
		}
	}
	
	private void  savedMessageClick(){
		Intent i = new Intent(this, SavedMessage.class);
		startActivity(i);
	}
	
	private void newMessageClick(){
		Intent i = new Intent(this, NewMessage.class);
		startActivity(i);
	}
	
	private void sendMessageClick(){
		Intent i = new Intent(this, SendMessage.class);
		startActivity(i);
	}
	
	private void logoutClick(){
		DatabaseHandler dbh = new DatabaseHandler(this);
		dbh.logoutCurrentUser();
		dbh.close();
		Intent login = new Intent(this, Login.class);
		startActivity(login);
	}
	
	public void onClick(View v){

		switch (v.getId()){
			case R.id.button2:
				savedMessageClick();
				break;
			case R.id.button1:
				newMessageClick();
				break;
			case R.id.button3:
				sendMessageClick();
				break;
			case R.id.button4:
				logoutClick();
				break;
		}
	}
	


	void startRepeatingTask()
	{
	    m_handlerTask.run(); 
	}

	void stopRepeatingTask()
	{
	    m_handler.removeCallbacks(m_handlerTask);
	}


}

